<template>
	<div class="system-authorize-dialog-container">
		<el-dialog :title="state.dialog.title" v-model="state.dialog.isShowDialog" width="90%" :close-on-click-modal="false" @close="close">
      <el-card shadow="hover" class="layout-padding-auto" style="height: 70vh">
        <div class="system-noRoleUser-search mb15">
          <el-button size="default" type="success" class="ml10" @click="onOpenAuthorizeAddDialog(state.tableData.param.userId)">
            <el-icon>
              <ele-FolderAdd />
            </el-icon>
            添加角色
          </el-button>
        </div>
        <el-table :data="state.tableData.data" v-loading="state.tableData.loading" style="width: 100%">
          <el-table-column type="index" label="序号" width="60" />
          <el-table-column prop="roleName" label="角色名称" width="150" show-overflow-tooltip></el-table-column>
          <el-table-column prop="roleCode" label="角色代码" width="150" show-overflow-tooltip></el-table-column>
          <el-table-column prop="orgName" label="角色所属机构" width="250" show-overflow-tooltip></el-table-column>
          <el-table-column prop="childName" label="学生名称（家长身份）" width="200" show-overflow-tooltip></el-table-column>
          <el-table-column prop="topOrgName" label="学生所属学校（家长身份）" width="200" show-overflow-tooltip></el-table-column>
          <el-table-column prop="gmtCreate" label="创建时间" show-overflow-tooltip></el-table-column>
          <el-table-column prop="gmtModified" label="修改时间" show-overflow-tooltip></el-table-column>
          <el-table-column label="操作" width="200">
            <template #default="scope">
              <el-button  size="small" text type="primary" @click="onRowDel(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
            @size-change="onHandleSizeChange"
            @current-change="onHandleCurrentChange"
            class="mt15"
            :pager-count="5"
            :page-sizes="[10, 20, 50]"
            v-model:current-page="state.tableData.param.current"
            background
            v-model:page-size="state.tableData.param.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="state.tableData.total"
        >
        </el-pagination>
      </el-card>
      <authorizeAddDialog ref="authorizeAddDialogRef" @refresh="refresh()" />
		</el-dialog>
	</div>
</template>

<script setup lang="ts" name="authorizeDialog">
import {defineAsyncComponent, reactive, ref} from 'vue';
import {userApi} from "/@/api/user";
import {ElMessage, ElMessageBox} from "element-plus";

// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh']);
const {findRoleListByUserId,UserRoleRelationshipRemoveById} = userApi();

const authorizeAddDialog = defineAsyncComponent(() => import('/src/views/system/noRole/authorizeAddDialog.vue'));
const authorizeAddDialogRef = ref();

// 定义变量内容
const state = reactive({
  tableData: {
    data: [],
    total: 0,
    loading: false,
    param: {
      current: 1,
      pageSize: 10,
      pageNum: 1,
      userId:'',
    },
  },
	dialog: {
		isShowDialog: false,
		title: '权限管理',
	},
});

// 打开弹窗
const openDialog = (userId: string) => {
	state.dialog.isShowDialog = true;
  state.tableData.param.userId=userId;
  getTableData();
};

const onOpenAuthorizeAddDialog = (userId: string) => {
  authorizeAddDialogRef.value.openDialog(userId);
};

// 打开弹窗
const refresh = () => {
  getTableData()
};
const close = () => {
  emit('refresh');
};

// 初始化表格数据
const getTableData = async () => {
  state.tableData.loading = true;
  const res = await findRoleListByUserId(state.tableData.param)
  if (res.status === 200) {
    state.tableData.data = res.data.records;
    state.tableData.total = res.data.total;
    state.tableData.loading = false;
  }
};

// 删除用户
const onRowDel = (row: any) => {
  ElMessageBox.confirm(`此操作将永久删除角色名称：“${row.roleName}”，关联机构为：“${row.orgName}”，是否继续?`, '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  })
      .then(async () => {
        if(row.roleCode=='TEACHER') {
          const hasSpecialRole = state.tableData.data.some((row1: any) => {
            return row.orgName == row1.orgName && (row1.roleCode === 'TEACHER_MANAGER' || row1.roleCode === 'SCHOOL_MANAGER');
          });

          if (hasSpecialRole) {
            ElMessage.error(`该用户在删除的机构“${row.orgName}”下还有管理员角色，请先删除`);
            return;
          }
        }
        const res = await UserRoleRelationshipRemoveById({id: row.id})
        if (res.status === 200) {
          await getTableData();
          ElMessage.success('删除成功');
        } else {
          ElMessage.error('删除失败');
        }
      })
};


const onHandleSizeChange = (val: number) => {
  state.tableData.param.pageSize = val;
  getTableData();
};
// 分页改变
const onHandleCurrentChange = (val: number) => {
  state.tableData.param.pageNum = val;
  getTableData();
};


// 暴露变量
defineExpose({
	openDialog,
});
</script>
